package a.b.mvc6.config;

import com.alibaba.fastjson2.support.spring6.data.redis.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching // 打开Spring缓存注解驱动
public class CacheConfig {

    @Autowired
    private Environment env;

    /**
     * 注册缓存管理器
     * @param connectionFactory Redis连接工厂
     * @return CacheManager
     */
    @Bean
    public CacheManager cacheManager(@Autowired RedisConnectionFactory connectionFactory){

        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration
                // 默认的缓存配置
                .defaultCacheConfig()
                // 通用缓存过期时间
                .entryTtl(Duration.ofMinutes(Long.parseLong(env.getProperty("cache.entry-ttl", "10"))))
                // Key 序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(StringRedisSerializer.UTF_8))
                // Values 序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()))
                // 禁用缓存空值
                .disableCachingNullValues();

        return RedisCacheManager
                .builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                // 在事务内操作时，缓存和数据库一致性更安全
                .transactionAware()
                .build();
    }
}
